package com.fintech.third.service.message;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fintech.common.enums.RespStatus;
import com.fintech.common.service.BaseServiceImpl;
import com.fintech.common.util.PropertiesUtils;
import com.fintech.third.constant.LocalStatus;
import com.fintech.third.constant.ThirdProductChannelConstant;
import com.fintech.third.constant.ThirdProductConstant;
import com.fintech.third.dao.SmsMapper;
import com.fintech.third.dao.SmsTemplateMapper;
import com.fintech.third.dao.ThirdProductChannelMappper;
import com.fintech.third.model.ReceiptStatusInfo;
import com.fintech.third.model.SdReceiptStatusInfo;
import com.fintech.third.model.ThirdProductChannel;
import com.fintech.third.model.message.MicroNetResponse;
import com.fintech.third.model.message.ResponseData;
import com.fintech.third.model.message.SmsDefinebathSend;
import com.fintech.third.model.message.SmsSend;
import com.fintech.third.model.message.SmsSendFailure;
import com.fintech.third.model.message.SmsTemplate;
import com.fintech.third.service.SmsChannelSend;
import com.fintech.third.service.SmsDataDeal;
import com.fintech.third.utils.SmsSendThread;
import com.marvels.common.utils.MarvelsLogUtil;

import net.sf.json.JSONObject;

@Service("Sms")
public class SmsImpl extends BaseServiceImpl implements SmsService {

	@Autowired
	private SmsMapper smsMapper;
	@Autowired
	private SmsTemplateMapper smsTemplateMapper;
	@Autowired
	private ThirdProductChannelMappper thirdProductChannelMappper;

	public String sendSms(JSONObject json) {
		SmsSendThread smsSendThread = new SmsSendThread();
		smsSendThread.setObject(json);
		Thread thread = new Thread(smsSendThread);
		thread.start();
		return "";
	}

	@Override
	public SmsTemplate querySmsTemplateById(long templateId) {
		SmsTemplate smsTemplate = new SmsTemplate();
		smsTemplate = smsTemplateMapper.obtainSmsTemplateContent(templateId);
		return smsTemplate;
	}

	@Override
	public String insertSmsTemplate(JSONObject json) {
		String errorMsg = "";
		SmsTemplate smsTemplate = new SmsTemplate();
		smsTemplate.setContent_template_document(json.get("content_template_document").toString());
		smsTemplate.setContent_template_name(json.get("content_template_name").toString());
		smsTemplate.setIs_user(Boolean.parseBoolean(json.get("is_user").toString()));
		int returnNum = 0;
		try {
			returnNum = smsTemplateMapper.insertSmsTemplate(smsTemplate);
		} catch (Exception e) {
			e.printStackTrace();
			MarvelsLogUtil.getInstance().info("============>>>插入短信模板:" + e.getMessage());
			return "插入短信模板失败!";
		}
		if (returnNum < 1) {
			errorMsg = "插入短信模板失败!";
		} else {
			errorMsg = "插入短信模板成功!";
		}
		return errorMsg;
	}

	@Override
	public String removeSmsTemplate(long templateId) {
		String errorMsg = "";
		int returnNum = 0;
		try {
			returnNum = smsTemplateMapper.removeSmsTemplate(templateId);
		} catch (Exception e) {
			e.printStackTrace();
			MarvelsLogUtil.getInstance().info("============>>>删除短信模板:" + e.getMessage());
			return "删除短信模板失败!";
		}
		if (returnNum < 1) {
			errorMsg = "删除短信模板失败";
		} else {
			errorMsg = "删除短信模板成功";
		}
		return errorMsg;
	}

	@Override
	public String updateSmsTemplate(JSONObject jsonObject) {
		String errorMsg = "";
		SmsTemplate smsTemplate = new SmsTemplate();
		smsTemplate.setId(Long.parseLong(jsonObject.get("id").toString()));
		smsTemplate.setContent_template_document(jsonObject.get("content_template_document").toString());
		smsTemplate.setContent_template_name(jsonObject.get("content_template_name").toString());
		smsTemplate.setIs_user(Boolean.parseBoolean(jsonObject.get("is_user").toString()));
		int returnNum = 0;
		try {
			returnNum = smsTemplateMapper.updateSmsTemplate(smsTemplate);
		} catch (Exception e) {
			e.printStackTrace();
			MarvelsLogUtil.getInstance().info("============>>>更新短信模板:" + e.getMessage());
			return "更新短信模板失败!";

		}
		if (returnNum < 1) {
			errorMsg = "更新短信模板失败!";
		} else {
			errorMsg = "更新短信模板成功!";
		}
		return errorMsg;
	}

	@Override
	public List<Map<String, Object>> searchSmsTemplateInfo(JSONObject jsonObject) {
		Map<String, Object> map = new HashMap<String, Object>();
		int currPage = 1;
		int pageSize = 20;
		int offset = 0;
		String tm_content_template = "";
		String content_template_document = "";
		int limit = 0;
		boolean is_user = false;
		if (!"".equals(jsonObject.get("currPage")) && jsonObject.get("is_user") != null) {
			currPage = Integer.parseInt(jsonObject.get("currPage").toString());
		}
		if (!"".equals(jsonObject.get("pageSize"))) {
			pageSize = Integer.parseInt(jsonObject.get("pageSize").toString());
		}
		if (!"".equals(jsonObject.get("content_template_name")) && jsonObject.get("is_user") != null) {
			tm_content_template = jsonObject.get("content_template_name").toString();
		}
		if (!"".equals(jsonObject.get("content_template_document")) && jsonObject.get("is_user") != null) {
			content_template_document = jsonObject.get("content_template_document").toString();
		}
		if (!"".equals(jsonObject.get("is_user")) && jsonObject.get("is_user") != null) {
			is_user = Boolean.parseBoolean(jsonObject.get("is_user").toString());
			map.put("is_user", is_user);
		}
		offset = (currPage - 1) * pageSize;
		limit = currPage * pageSize;
		map.put("tm_content_template", tm_content_template);
		map.put("content_template_document", content_template_document);
		map.put("offset", offset);
		map.put("limit", limit);

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = smsTemplateMapper.searchSmsTemplateInfo(map);
		} catch (Exception e) {
			e.printStackTrace();
			MarvelsLogUtil.getInstance().info("============>>>查询短信模板信息:" + e.getMessage());
			return null;
		}
		return list;
	}

	@Override
	public String smsSendAgagin(long smsSendFailureId) {
		/*
		 * 如果接口停用，直接返回（视具体情况，有的返回停用，有的返回相关值） ADD BY TUXU 2018-05-31
		 */
		if (PropertiesUtils.isTurnOffForSwitch("switch.sms001")) {
			// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
			return RespStatus.DISABLE.getCode()+"";
		}
		String status = LocalStatus.REQUEST_FAIL.getCode(); // 默认请求失败
		String thirdCode = null;
		Date startDate = new Date();
		String thirdMethodConstants = null; // 接口名
		SmsSendFailure smsSendFailure = new SmsSendFailure();
		smsSendFailure = smsMapper.obtainSmsSendFailureInfo(smsSendFailureId);
		List<ThirdProductChannel> thirdProductChannelList = new ArrayList<ThirdProductChannel>();
		thirdProductChannelList = thirdProductChannelMappper
				.queryThirdProductChannel(ThirdProductConstant.SMS.getCode());
		SmsDataDeal smsSendDeal = new SmsDataDeal();
		String errorMsg = "";
		ResponseData responseData = null;
		String phone = smsSendFailure.getPhone();
		String templateContent = smsSendFailure.getMsg();
		String createTime = smsSendFailure.getCreate_time();
		String templateId = String.valueOf(smsSendFailure.getTemplate_id());
		String src = smsSendFailure.getSrc();
		for (ThirdProductChannel productChannelDto : thirdProductChannelList) {
			String channelCode = productChannelDto.getCode();
			try {
				if (productChannelDto != null
						&& ThirdProductChannelConstant.TRUETESTSMS.getCode().equals(channelCode)) {// 中正云通讯短信
					String string = SmsChannelSend.middleClubSms(phone, templateContent);
					String[] strings = string.split("/");
					if ("000".equals(strings[0])) {
						smsSendDeal.dealSmsSendInfo(createTime, templateId, src, templateContent, phone, "", "", "", "",
								channelCode);
						smsMapper.deleteSmsSendFailureInfo(smsSendFailureId);
						errorMsg = "短信重发成功!";

						status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
					} else {
						smsMapper.updateSmsSendFailureInfo(smsSendFailureId);
						errorMsg = "短信重发失败!";
						status = LocalStatus.REQUEST_FAIL.getCode();
					}
					thirdCode = strings[0];
					thirdMethodConstants = ThirdProductChannelConstant.TRUETESTSMS.getCode();
					break;
				} else if (productChannelDto != null
						&& ThirdProductChannelConstant.TENCENTSMS.getCode().equals(channelCode)) {// 腾讯云短信
					responseData = SmsChannelSend.tencentSms(phone, templateContent);
					MarvelsLogUtil.getInstance().info("send_note_error===>>" + responseData.getError());
					JSONObject result_json = JSONObject.fromObject(responseData.getBody());
					if (responseData.getBody() != null && "0".equals(result_json.get("result"))) {
						smsSendDeal.dealSmsSendInfo(createTime, templateId, src, templateContent, phone, "", "", "", "",
								channelCode);
						errorMsg = "短信重发成功!";

						status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
					} else {
						smsMapper.updateSmsSendFailureInfo(smsSendFailureId);
						errorMsg = "短信重发失败!";
						status = LocalStatus.REQUEST_FAIL.getCode();
					}
					thirdCode = result_json.get("result") + "";
					thirdMethodConstants = ThirdProductChannelConstant.TENCENTSMS.getCode();
					break;
				} else if (productChannelDto != null
						&& ThirdProductChannelConstant.MICRONETCOMSMS.getCode().equals(channelCode)) {// 微网通联短信
					MicroNetResponse microNetResponse = SmsChannelSend.microNetcomSms(phone, templateContent,
							smsSendFailure.getMessage_category());
					if ("0".equals(microNetResponse.getState())) {
						errorMsg = "短信重发成功!";
						smsSendDeal.dealSmsSendInfo(createTime, templateId, src, templateContent, phone, "", "",
								microNetResponse.getMsgID(), "", channelCode);

						status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
					} else {
						errorMsg = "短信重发失败!";
						smsSendDeal.dealSmsSendFailure(createTime, templateId, src, templateContent, phone, "", "",
								microNetResponse.getMsgID(), "", channelCode, "");
						status = LocalStatus.REQUEST_FAIL.getCode();
					}
					thirdCode = microNetResponse.getState();
					thirdMethodConstants = ThirdProductChannelConstant.MICRONETCOMSMS.getCode();
				}
				break;
			} catch (Exception e) {
				e.printStackTrace();
				smsMapper.updateSmsSendFailureInfo(smsSendFailureId);
				MarvelsLogUtil.getInstance().info("============>>>短信重发:" + e.getMessage());
				return "短信重发失败!";
			}

		}

		// 记入统一日志表
		saveDataQueryLog(System.currentTimeMillis() + "_" + RandomStringUtils.randomAlphanumeric(6), phone, phone, null,
				startDate, new Date(), thirdMethodConstants, thirdCode, status, "edc_sms_data_query_log", "system");
		return errorMsg;
	}

	@Override
	public Boolean insertTimingSms(List<SmsSend> list) {
		try {
			smsMapper.insertTimingSms(list);
			return true;
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().info("========批量插入定时短信异常======");
			e.printStackTrace();
			return false;
		}

	}

	@Override
	public Boolean smsSendDefineTemplate(final List<SmsDefinebathSend> list) {
		return true;
	}

	@Override
	public void updateReceiptStatus(ReceiptStatusInfo receiptStatusInfo) {
		if (receiptStatusInfo != null) {
			MarvelsLogUtil.getInstance().info("===========(微网通联)短信状态报告回调状态信息:" + JSONObject.fromObject(receiptStatusInfo));
			String status = "";
			if (receiptStatusInfo.isReportState()) {
				status = "0";
			} else {
				status = "-1";
			}
			if (smsMapper.updateSmsSendByMsgId(status, receiptStatusInfo.getMsgID()) == 0) {
				smsMapper.updateSmsSendFailureByMsgId(status, receiptStatusInfo.getMsgID());
			}
		}
		return;
	}

	@Override
	public void sdReceiptStatus(SdReceiptStatusInfo sdReceiptStatusInfo) {
		if (sdReceiptStatusInfo != null) {
			MarvelsLogUtil.getInstance().info("===========(速盾)短信状态报告回调状态信息:" + JSONObject.fromObject(sdReceiptStatusInfo));
			String status = "";
			if (("DELIVRD").equals(sdReceiptStatusInfo.getStatus())) {
				status = "0";
			} else {
				status = "-1";
			}
			if (smsMapper.updateSmsSendByMsgId(status, sdReceiptStatusInfo.getMsgid()) == 0) {
				smsMapper.updateSmsSendFailureByMsgId(status, sdReceiptStatusInfo.getMsgid());
			}
		}
		return;
	}

	@Override
	public void fhReceiptStatus(String name, String report) {
		MarvelsLogUtil.getInstance().info("===========(北京北京烽火短信)短信状态报告回调状态信息:" + report);
		if (StringUtils.isNotEmpty(report)) {
			try {

				List<String> list = Arrays.asList(report.split(";"));
				for (String string : list) {
					String[] strings = string.split(",");
					String msgId = strings[0];
					String phone = strings[1];
					String status = strings[2];
					String sendTime = strings[3];
					if (status.equals("DELIVRD")) {// 成功
						status = "0";
					} else {
						status = "-1";
					}
					if (smsMapper.updateSmsSendByMsgId(status, msgId) == 0) {
						smsMapper.updateSmsSendFailureByMsgId(status, msgId);
					}
				}

			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error("=======北京烽火短信回调:"+e);
			}
		}
	}
}
